<template>
  <div class="image-upload" :class="{disabled:isdisabled}">
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :limit="limit"
      :on-exceed="onExceed"
      :on-remove="handleRemove"
      :http-request="httpRequest"
      :on-change="onChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="头像预览" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import cos from '@/utils/cos'
export default {
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  computed: {
    isdisabled () {
      return this.fileList.length >= this.limit
    },
    isAllUploadSuccess () {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    beforeUpload (file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
    },
    onChange (file, fileList) {
      this.fileList = fileList
    },
    httpRequest ({ file }) {
      const curfile = this.fileList.find(item => item.uid === file.uid)
      if (!file) return
      curfile.status = 'uploading'
      cos.putObject({
        Bucket: 'ruanshizi-1316190581', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: +new Date() + file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        onProgress: function (progressData) {
          curfile.percentage = progressData.percent * 100
        }
      }, function (err, data) {
        if (err) {
          this.$message.error('上传失败，请稍后再试')
          return
        }
        curfile.url = '//' + data.Location
        setTimeout(() => {
          curfile.status = 'success'
        }, 500)
      })
    },
    onExceed () {
      this.$message.warning('达到上传数量上线')
    },
    handleRemove (file, fileList) {
      // 第一种 fileList 就是剩下的未删除的图片所组成的数组
      // this.fileList = [...fileList]
      // 第二种  file 就是删除的该图片信息
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled{
	::v-deep{
		.el-upload--picture-card{
		display: none;
	}
	}
}
</style>
